package com.webside.points.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.webside.points.wechat.HttpUtil;
import com.webside.points.wechat.RandomGenerator;
import com.webside.points.wechat.Signature;
import com.webside.points.wechat.WeChatConfig;
import com.webside.points.wechat.Wechat;
import com.webside.points.wechat.WxPayApi;


@Controller
@Scope("prototype")
@RequestMapping("/wechat/")
public class WechatController {
	
	private static String jsapi_ticket = null;

	private static Date beginTime = null;

	private static final int CACHETIME = 7200;

	
	@RequestMapping("getWeChatCode")
	public void getWeChatCode(HttpServletResponse response,HttpServletRequest request){
		
		System.out.println("url:>>>"+request.getParameter("url"));
		
		System.out.println("进入获取Code方法");
		Wechat.requestCode(response,request);
	}
	
	@RequestMapping("getRewardOrder")
	@ResponseBody
	public String getRewardOrder(String openId,String amount,HttpServletRequest request){
		
		System.out.println("打赏进入统一支付");
		return Wechat.getRewardOrder(openId, amount, request);
	}
	
	@RequestMapping("getStudyOrder")
	@ResponseBody
	public String getStudyOrder(String openId,String amount,int userId,int postTypeId,HttpServletRequest request){
		
		System.out.println("学习进入统一支付");
		return Wechat.getRStudyOrder(openId, amount, userId ,postTypeId , request);
	}
	
	@RequestMapping("getWxSignatureByTicket")
	@ResponseBody
	public static String getWxSignatureByTicket(String url,HttpServletRequest request, HttpServletResponse response) {
		//System.out.println("进入jssdk接口：>>>"+issueTypeId+"    "+openId);
		Map<?, ?> result = null;
		ObjectMapper mapper = new ObjectMapper();
		// 两小时内缓存jsapi_ticket
		if (beginTime == null || (new Date().getTime()-beginTime.getTime())/1000 > CACHETIME) {
			
			String accessTokenJson = Wechat.accessToken();

			System.out.println("accessTokenJson:>>>"+accessTokenJson);

			try {
				// 第一步：获取Access_Token
				result = mapper.readValue(accessTokenJson, Map.class);

				// 第二步：根据Access_Token获取ticket
				StringBuffer ticket = new StringBuffer();
				ticket.append(WeChatConfig.JSAPI_TICKET_URL);
				ticket.append("?access_token=" + result.get("access_token"));
				ticket.append("&type=jsapi");
				String ticketJson = HttpUtil.sendGet(ticket.toString());
				result = mapper.readValue(ticketJson, Map.class);
				jsapi_ticket = (String) result.get("ticket");
				beginTime = new Date();
				
				System.out.println("ticketJson:>>>"+ticketJson);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 第三步：签名
		Map<String, String> map = new HashMap<String, String>();
		String noncestr = RandomGenerator.getRandomStringByLength(16);
		String timestamp = Long.toString(System.currentTimeMillis() / 1000);
		//String url = "http://wenda.2muslim.org/points/service/character-issue.jsp?issueTypeId="+issueTypeId+"&openId="+openId+"&type=issue";
		System.out.println("url:>>>"+url.toString());
		map.put("noncestr", noncestr);
		map.put("timestamp", timestamp);
		map.put("jsapi_ticket", jsapi_ticket);
		map.put("url", url.toString());
		String signature = Signature.getSHA1Sign(map);

		Map<String, String> resultJson = new HashMap<String, String>();
		resultJson.put("noncestr", noncestr);
		resultJson.put("timestamp", timestamp);
		resultJson.put("signature", signature);
		resultJson.put("appId", WeChatConfig.APP_ID);

		try {
			return mapper.writeValueAsString(resultJson);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		return null;
	}
	@RequestMapping("mediaGet")
	@ResponseBody
	public static String mediaGet(String mediaId,String savePath,HttpServletRequest request,HttpServletResponse response){
		
		System.out.println("mediaId:>>>："+mediaId+" savePath>>>:"+savePath);
		
		String path=request.getSession().getServletContext().getRealPath("/")+ savePath;
		
		System.out.println(path);
		
		String filePath = Wechat.mediaGet(mediaId, path);
		
		if(filePath.contains(".amr")){
			boolean bool = WxPayApi.change(filePath,filePath.replace(".amr", ".mp3"));	
			System.out.println("bool:>>>"+bool);
			/*if(bool==true){
				//删除amr格式文件
				filePath = filePath.replace("C:\\xampp\\tomcat\\webapps\\points\\", "C:\\xampp\\tomcat\\webapps\\points/");
				//C:\xampp\tomcat\webapps\points/upload/fYH8KYDcNyvsMnBvN6KSjeIo-fK-QiWOhj6rBIjX4M4hsP7tgevTXdQO6LqtyRmw.amr
				System.out.println("filePath:>>>"+filePath);
				File file=new File(filePath);
				file.delete();
			}*/
			
			filePath = filePath.replace(".amr", ".mp3");
			
		}
		//filePath = filePath.replace("/usr/local/tomcat/webapps/points/", "../");
		filePath = filePath.replace("C:\\xampp\\tomcat\\webapps\\points\\", "../");
		
		
		System.out.println("文件路径：>>>"+filePath);
		
		return filePath;
			
	}
	
	
}
